package com.example.controller;

import com.example.common.Result;
import com.example.entity.ReaderMessage;
import com.example.entity.UserMessage;
import com.example.entity.VolunteerMessage;
import com.example.service.ReaderMessageService;
import com.example.service.UserMessageService;
import com.example.service.VolunteerMessageService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @author 紫煦桉
 */
@Controller
public class LoginController {
    private final Logger logger = Logger.getLogger(LoginController.class);

    private UserMessageService userMessageService;
    private ReaderMessageService readerMessageService;
    private VolunteerMessageService volunteerMessageService;
    @Autowired
    private void setUserMessageService(UserMessageService userMessageService, ReaderMessageService readerMessageService, VolunteerMessageService volunteerMessageService) {
        this.userMessageService = userMessageService;
        this.readerMessageService = readerMessageService;
        this.volunteerMessageService = volunteerMessageService;
    }

    @RequestMapping("/login")
    @ResponseBody
    public Result login(UserMessage userMessage, ReaderMessage readerMessage, VolunteerMessage volunteerMessage, String validate, HttpSession session) {
        Result result = null;
        String rand = (String) session.getAttribute("rand");
        if (rand != null && rand.equalsIgnoreCase(validate)) {
            try{UserMessage messageUser = userMessageService.login(userMessage);
            ReaderMessage messageReader = readerMessageService.login(readerMessage);
            VolunteerMessage messageVolunteer = volunteerMessageService.login(volunteerMessage);
            if (messageUser != null || messageReader != null || messageVolunteer != null) {
                logger.info("登录成功!" + userMessage);
                session.setAttribute("user_login", userMessage);
                result = new Result(Boolean.TRUE, "登录成功!");
            } else {
                result = new Result(Boolean.FALSE, "登录失败!");
            }}catch(Exception e){e.printStackTrace();}
        } else {
            result = new Result(Boolean.FALSE, "验证码错误!");
        }
        return result;
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
//        使登陆信息失效，会话结束
        session.invalidate();
//        重定向
        return "redirect:/login.jsp";
    }

}
